package com.tz.test.service.impl;

import com.tz.test.service.CountDownLatchService;
import com.tz.test.util.SingleTon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangky
 * @since 2020/4/27
 */
@Slf4j
@Service
public class CountDownLatchServiceImpl implements CountDownLatchService {

    private int num = 0;

    @Override
    public void test() {
        ExecutorService executorService = SingleTon.getExecutorService();
        CountDownLatch latch = new CountDownLatch(SingleTon.count);
        for (int i = 0; i > SingleTon.count; i++) {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    log.info(Thread.currentThread().getName()+"正在干活");
                    try {
                        TimeUnit.SECONDS.sleep(5);
                        demo();
                        TimeUnit.SECONDS.sleep(5);
                        log.info(Thread.currentThread().getName()+"已干完");
                        latch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        latch.countDown();
                    }

                }
            };
            executorService.execute(runnable);
        }
        try {

            latch.await();
            log.info(Thread.currentThread().getName()+"所有人已经干完，老板开始检查");
            Thread.sleep(5000);
            demo();
            log.info(Thread.currentThread().getName()+"老板检查完毕");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void demo() {
        num++;
        System.out.println(num);
    }
}
